<template>
  <div class="dialog_box" v-if="visible">
    <div class="right">
      <!-- 新增：智能体标题栏 -->
      <div class="dialog-header">
        <div class="agent-info">
          <div class="agent-avatar">
            <img
              src="../../assets/img/icon-ai.png"
              alt="AI Agent"
              class="agent-avatar-image"
            />
          </div>
          <div class="agent-details">
            <h3 class="agent-name">
              AI{{ selectedTypeInfo.name || "智能助手" }}
            </h3>
            <p class="agent-description">
              {{ selectedTypeInfo.description || "为您提供智能问答服务" }}
            </p>
          </div>
        </div>
        <div class="connection-status">
          <span class="status-dot online"></span>
          <span class="status-text">在线</span>
        </div>
      </div>

      <div class="talk_1" ref="chatContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="message_item"
          :class="message.role"
        >
          <div
            v-if="message.role == 'ai' && message.isWelCome"
            class="message_item_center"
          >
            <div class="img_avatar img_avatar_ai">
              <img
                src="../../assets/img/icon-ai.png"
                alt="AI"
                class="avatar-image"
              />
            </div>
            <div class="message-content">
              <div class="msg_hd" style="font-weight: bold; font-size: 20px">
                {{ message.headerCon }}
              </div>
              <div class="msg_main">
                <div
                  class="msg_main_item"
                  v-for="(item, index) in message.mainArr"
                  :key="index"
                  style="display: flex; align-items: center"
                >
                  <span
                    style="
                      display: block;
                      width: 5px;
                      height: 5px;
                      border-radius: 50%;
                      background-color: #fff;
                      margin-right: 6px;
                    "
                  ></span>
                  <span
                    style="
                      display: block;
                      text-decoration: underline;
                      text-decoration-color: #fff;
                      cursor: pointer;
                    "
                    @click="funSetInput(item)"
                    >{{ item }}</span
                  >
                </div>
              </div>
            </div>
            <span v-if="message.isTyping" class="typing-cursor">|</span>
          </div>
          <div v-else class="message_item_center">
            <div v-show="message.role == 'ai'" class="img_avatar img_avatar_ai">
              <img
                src="../../assets/img/icon-ai.png"
                alt="AI"
                class="avatar-image"
                :class="{
                  'ai-thinking': message.isTyping && !message.content,
                  'ai-speaking': message.isTyping && message.content,
                }"
              />
              <!-- AI状态指示器 -->
              <div v-if="message.isTyping" class="ai-status-indicator">
                <div class="thinking-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>

            <div
              class="message-content"
              :class="{
                'typing-animation': message.isTyping,
                streaming: message.isStreaming,
              }"
            >
              <!-- AI思考中状态 -->
              <div
                v-if="message.isTyping && !message.content"
                class="ai-thinking-text"
              >
                正在思考中<span class="thinking-dots-text">
                  <span class="dot">.</span>
                  <span class="dot">.</span>
                  <span class="dot">.</span>
                </span>
              </div>
              <!-- 流式输出的内容 -->
              <div
                v-else-if="message.content"
                class="streaming-content markdown-content"
                v-html="message.renderedContent"
              ></div>
            </div>

            <div
              v-show="message.role == 'user'"
              class="img_avatar img_avatar_user"
            >
              <img
                src="../../assets/img/user_icon.png"
                alt="User"
                class="avatar-image"
              />
            </div>

            <!-- 流式输出光标 -->
            <span
              v-if="message.isTyping && message.content"
              class="streaming-cursor"
              >▌</span
            >
          </div>
        </div>
      </div>

      <div class="talk_2">
        <el-input
          v-model="userInput"
          class="message-input"
          type="textarea"
          :rows="3"
          :disabled="isAIResponding"
          @keyup.enter="sendMessage"
          :placeholder="`向AI${selectedTypeInfo.name || 'AI智能助手'}提问...`"
          resize="none"
          autofocus
        />
        <div class="detail">
          <div class="num">已输入 {{ userInput.length || 0 }} 字</div>
          <button
            @click="handleAction"
            class="send-button"
            :disabled="isAIResponding && !isAbortable"
            :class="{ 'abort-button': isAIResponding && isAbortable }"
          >
            {{ getButtonText }}
          </button>
        </div>
      </div>
      <div class="close-btn" @click="closeDia">
        <i class="el-icon-close" style="font-size: 18px; color: #fff"></i>
      </div>
    </div>
  </div>
</template>

<script>
  import axios from "axios";
  import { marked } from "marked";
  import hljs from "highlight.js";
  import "highlight.js/styles/atom-one-dark.css"; // 可根据需要选择主题
  import {
    getCurrYMD,
    formatTimestamp,
    generateSecureRandomString,
  } from "@/utils/screen/commFun.js";

  // 配置 marked 和代码高亮
  const renderer = new marked.Renderer();

  // 自定义代码块渲染
  renderer.code = (code, language) => {
    const validLanguage = hljs.getLanguage(language) ? language : "plaintext";
    const highlighted = hljs.highlight(code, { language: validLanguage }).value;
    return `<pre class="hljs-code-block"><code class="hljs language-${validLanguage}">${highlighted}</code></pre>`;
  };

  // 自定义行内代码渲染
  renderer.codespan = (code) => {
    return `<code class="hljs-inline-code">${code}</code>`;
  };

  // 配置 marked 选项
  marked.setOptions({
    renderer: renderer,
    highlight: function (code, language) {
      const validLanguage = hljs.getLanguage(language) ? language : "plaintext";
      return hljs.highlight(code, { language: validLanguage }).value;
    },
    langPrefix: "hljs language-",
    pedantic: false,
    gfm: true,
    breaks: true,
    sanitize: false,
    smartLists: true,
    smartypants: false,
    xhtml: false,
  });

  export default {
    name: "ConversationDialog",
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      selectedTypeInfo: {
        type: Object,
        default: () => ({}),
      },
    },
    data() {
      return {
        messages: [],
        userInput: "",
        isAIResponding: false,
        isAbortable: false,
        currChartId: generateSecureRandomString(),
        abortController: null,
        lastMessageId: 0,
        flowData: null,
        // 新增：打字机效果相关
        typewriterQueue: [], // 待打字的内容队列
        isTyping: false, // 是否正在打字
        typewriterSpeed: 30, // 打字速度(毫秒)
      };
    },
    computed: {
      getButtonText() {
        return this.isAIResponding
          ? this.isAbortable
            ? "停止回答"
            : "响应中..."
          : "发送";
      },
      // 从父组件获取token
      currToken() {
        return this.$parent.currTokey || "";
      },
    },
    watch: {
      visible(newVal) {
        if (newVal) {
          this.initChat();
        } else {
          this.resetChat();
        }
      },
    },
    methods: {
      // 新增：渲染 Markdown 内容
      renderMarkdown(content) {
        try {
          return marked(content);
        } catch (error) {
          console.error("Markdown 渲染错误:", error);
          return content.replace(/\n/g, "<br>");
        }
      },

      async initChat() {
        try {
          if (this.currToken) {
            await this.funInitChat();
          } else {
            console.warn("未找到有效的token");
          }
        } catch (error) {
          console.error("初始化聊天失败:", error);
        }
      },

      resetChat() {
        // 取消正在进行的请求
        if (this.abortController) {
          this.abortController.abort();
          this.abortController = null;
        }
        this.messages = [];
        this.userInput = "";
        this.isAIResponding = false;
        this.isAbortable = false;
        // 重新生成聊天ID
        this.currChartId = generateSecureRandomString();
        this.lastMessageId = 0;

        // 清理打字机状态
        this.typewriterQueue = [];
        this.isTyping = false;
      },

      async funInitChat() {
        try {
          if (!this.currToken) return;

          const response = await axios.post(
            "/huayun-ai/client/chat/new/init",
            {
              tenantAppId: this.$store.state.chatModuleId,
              chatId: "",
              accessKey: this.currToken,
            },
            {
              headers: {
                Authorization: this.$store.state.chatToken,
              },
            }
          );

          const resD = response;
          console.log("初始化接口返回数据:", resD);

          if (resD.code == 200) {
            // 获取欢迎语
            let welcomeText = null;
            if (resD.data && resD.data.app && resD.data.app.chatConfig) {
              welcomeText = resD.data.app.chatConfig.welcomeText;
            }

            console.log("解析出的欢迎语:", welcomeText);

            // 如果没有欢迎语，设置默认欢迎语
            if (!welcomeText) {
              welcomeText = `欢迎使用${
                this.selectedTypeInfo.name || "AI智能助手"
              }！\n\n您可以向我询问相关问题，我将竭诚为您服务。`;
            }

            // 解析欢迎语配置
            const parsed = this.parseChatConfig(welcomeText);
            console.log("解析后的配置:", parsed);

            // 添加欢迎消息到消息列表
            const welcomeMessage = {
              id: ++this.lastMessageId,
              role: "ai",
              content: welcomeText,
              renderedContent: this.renderMarkdown(welcomeText),
              isTyping: false,
              isWelCome: true,
              headerCon:
                parsed && parsed.headerCon
                  ? parsed.headerCon
                  : `欢迎使用${this.selectedTypeInfo.name || "AI智能助手"}`,
              mainArr: parsed && parsed.mainArr ? parsed.mainArr : [],
            };

            this.messages.push(welcomeMessage);

            // 滚动到底部
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          } else {
            console.warn("初始化失败:", resD.msg);
            // 添加错误提示消息
            const errorMsg = `初始化失败: ${resD.msg || "未知错误"}`;
            this.messages.push({
              id: ++this.lastMessageId,
              role: "ai",
              content: errorMsg,
              renderedContent: this.renderMarkdown(errorMsg),
              isTyping: false,
              isWelCome: false,
            });
          }
        } catch (error) {
          console.error("初始化聊天失败:", error);

          // 添加错误提示消息
          const errorMsg = `连接失败，请检查网络后重试。错误信息: ${error.message}`;
          this.messages.push({
            id: ++this.lastMessageId,
            role: "ai",
            content: errorMsg,
            renderedContent: this.renderMarkdown(errorMsg),
            isTyping: false,
            isWelCome: false,
          });

          throw error;
        }
      },

      parseChatConfig(welcomeText) {
        if (!welcomeText) return null;

        const result = {
          headerCon: "",
          mainArr: [],
          headerLevel: 0,
        };

        // 按换行符分割文本
        const lines = welcomeText.split("\n").filter((line) => line.trim());

        if (lines.length > 0) {
          const firstLine = lines[0].trim();

          // 检查是否是markdown标题格式
          const headerMatch = firstLine.match(/^(#{1,6})\s*(.*)/);
          if (headerMatch) {
            result.headerLevel = headerMatch[1].length;
            result.headerCon = headerMatch[2].trim();
          } else {
            // 如果第一行不是标题格式，使用智能体名称作为标题
            result.headerCon = `${
              "AI" + this.selectedTypeInfo.name || "AI智能助手"
            }为您服务`;
          }
        }

        // 提取所有方括号内的内容作为快捷问题
        const regex = /\[([^\]]+)\]/g;
        let match;
        while ((match = regex.exec(welcomeText)) !== null) {
          const question = match[1].trim();
          if (question && !result.mainArr.includes(question)) {
            result.mainArr.push(question);
          }
        }

        // 如果没有提取到快捷问题，添加一些默认的
        if (result.mainArr.length === 0 && this.selectedTypeInfo.quickQueries) {
          result.mainArr = this.selectedTypeInfo.quickQueries.slice(0, 4);
        }

        return result;
      },

      handleAction() {
        if (this.isAIResponding && this.isAbortable) {
          this.abortResponse();
        } else {
          this.sendMessage();
        }
      },

      abortResponse() {
        if (this.abortController) {
          this.abortController.abort();
          this.abortController = null;
          this.isAIResponding = false;
          this.isAbortable = false;

          // 停止打字机效果
          this.typewriterQueue = [];
          this.isTyping = false;

          // 找到最后一个AI消息并停止其打字状态
          const lastAiMessage = [...this.messages]
            .reverse()
            .find((m) => m.role === "ai");
          if (lastAiMessage) {
            this.$set(lastAiMessage, "isTyping", false);
            this.$set(lastAiMessage, "isStreaming", false);
          }

          this.$message.info("已停止生成回答");
        }
      },

      async sendMessage() {
        if (!this.userInput.trim() || this.isAIResponding) {
          if (!this.userInput.trim()) {
            this.$message.error("输入内容不能为空");
          } else {
            this.$message.warning("AI正在回答中，请稍后再试");
          }
          return;
        }

        const userMessage = {
          id: ++this.lastMessageId,
          role: "user",
          content: this.userInput,
          renderedContent: this.renderMarkdown(this.userInput),
          isTyping: false,
        };
        this.messages.push(userMessage);

        const question = this.userInput;
        this.userInput = ""; // 清空输入框

        this.$nextTick(() => {
          this.scrollToBottom();

          const aiMessage = {
            id: ++this.lastMessageId,
            role: "ai",
            content: "",
            renderedContent: "",
            isTyping: true,
          };
          this.messages.push(aiMessage);

          this.isAIResponding = true;
          this.isAbortable = true;

          // 添加思考延迟效果
          setTimeout(() => {
            this.callAIChatAPI(question, aiMessage);
          }, 800);
        });
      },

      // 修改：点击快捷问题时自动发送
      async funSetInput(data) {
        console.log(123, data);
        // 直接发送问题，不填充到输入框
        await this.sendQuickQuestion(data);
      },

      // 新增：发送快捷问题的方法
      async sendQuickQuestion(question) {
        // 检查是否正在响应中
        if (this.isAIResponding) {
          this.$message.warning("AI正在回答中，请稍后再试");
          return;
        }

        // 创建用户消息
        const userMessage = {
          id: ++this.lastMessageId,
          role: "user",
          content: question,
          renderedContent: this.renderMarkdown(question),
          isTyping: false,
        };
        this.messages.push(userMessage);

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();

          // 创建AI消息
          const aiMessage = {
            id: ++this.lastMessageId,
            role: "ai",
            content: "",
            renderedContent: "",
            isTyping: true,
          };
          this.messages.push(aiMessage);

          this.isAIResponding = true;
          this.isAbortable = true;

          // 添加思考延迟效果
          setTimeout(() => {
            this.callAIChatAPI(question, aiMessage);
          }, 800);
        });
      },

      async callAIChatAPI(question, aiMessage) {
        try {
          if (!this.currToken) {
            throw new Error("Token无效，请重新初始化");
          }

          this.abortController = new AbortController();

          let _Timestamp = new Date().getTime();
          let params = {
            chatAppId: this.$store.state.chatModuleId,
            tenantAppId: this.$store.state.chatModuleId,
            chatId: this.currChartId,
            responseChatItemId: generateSecureRandomString(),
            messages: [
              {
                dataId: generateSecureRandomString(),
                role: "user",
                hideInUI: false,
                content: question,
              },
            ],
            variables: {
              cTimestamp: _Timestamp,
              cTime: formatTimestamp(_Timestamp),
            },
            detail: true,
            stream: true,
          };

          const response = await fetch("/huayun-ai/client/chat/completions", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              Authorization: this.$store.state.chatToken,
            },
            body: JSON.stringify(params),
            signal: this.abortController.signal,
          });

          if (!response.ok || !response.body) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          await this.processStreamResponse(response, aiMessage);
        } catch (error) {
          this.handleAPIError(error, aiMessage);
        }
      },

      async processStreamResponse(response, aiMessage) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8");
        let buffer = "";
        let isDone = false;

        // 标记为流式输出状态
        this.$set(aiMessage, "isStreaming", true);

        // 初始化打字机队列
        this.typewriterQueue = [];
        let accumulatedContent = "";

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          buffer += decoder.decode(value, { stream: true });

          const eventBlocks = buffer.split(/(?=event: \w+\r?\ndata: )/);
          buffer = eventBlocks.pop() || "";

          for (const block of eventBlocks) {
            const [_, eventType, eventData] =
              block.match(/event: (\w+)\r?\ndata: ([\s\S]*)/) || [];
            if (!eventType) continue;

            if (eventType === "answer") {
              if (eventData.trim() === "[DONE]") {
                isDone = true;
                continue;
              }

              try {
                const data = JSON.parse(eventData);
                let content = null;
                if (
                  data &&
                  data.choices &&
                  data.choices[0] &&
                  data.choices[0].delta
                ) {
                  content = data.choices[0].delta.content;
                }

                if (content) {
                  accumulatedContent += content;

                  // 将新内容添加到打字机队列
                  this.addToTypewriterQueue(content, aiMessage);
                }
              } catch (e) {
                console.warn("answer解析失败:", e);
              }
            }

            if (eventType === "flowResponses" && isDone) {
              try {
                const flowData = JSON.parse(eventData);
                console.log("流程数据:", flowData);
              } catch (e) {
                console.warn("flowResponses解析失败:", e);
              }
            }
          }
        }

        // 等待所有打字机效果完成
        await this.waitForTypewriterComplete();

        // 完成流式输出
        this.$set(aiMessage, "isTyping", false);
        this.$set(aiMessage, "isStreaming", false);
        this.isAIResponding = false;
        this.isAbortable = false;

        // 添加完成动画效果
        this.$nextTick(() => {
          const messageElements = document.querySelectorAll(
            ".message_item.ai .message-content"
          );
          const lastMessage = messageElements[messageElements.length - 1];
          if (lastMessage) {
            lastMessage.classList.add("message-complete");
            setTimeout(() => {
              lastMessage.classList.remove("message-complete");
            }, 500);
          }
        });
      },

      // 新增：添加内容到打字机队列
      addToTypewriterQueue(content, aiMessage) {
        this.typewriterQueue.push({
          content,
          aiMessage,
        });

        // 如果没在打字，开始打字机效果
        if (!this.isTyping) {
          this.startTypewriter();
        }
      },

      // 新增：开始打字机效果
      async startTypewriter() {
        if (this.isTyping || this.typewriterQueue.length === 0) return;

        this.isTyping = true;

        while (this.typewriterQueue.length > 0) {
          const { content, aiMessage } = this.typewriterQueue.shift();
          await this.typeText(content, aiMessage);
        }

        this.isTyping = false;
      },

      // 修改：逐字打字效果，支持 Markdown 渲染
      async typeText(newContent, aiMessage) {
        const chars = newContent.split("");
        let currentRawContent = aiMessage.content || "";

        for (let i = 0; i < chars.length; i++) {
          // 检查是否被中断
          if (!aiMessage.isTyping) break;

          currentRawContent += chars[i];

          // 更新原始内容
          this.$set(aiMessage, "content", currentRawContent);

          // 渲染 Markdown 内容
          const renderedContent = this.renderMarkdown(currentRawContent);
          this.$set(aiMessage, "renderedContent", renderedContent);

          // 滚动到底部
          this.$nextTick(() => this.scrollToBottom());

          // 打字延迟
          await new Promise((resolve) =>
            setTimeout(resolve, this.typewriterSpeed)
          );
        }
      },

      // 新增：等待打字机完成
      async waitForTypewriterComplete() {
        return new Promise((resolve) => {
          const checkComplete = () => {
            if (!this.isTyping && this.typewriterQueue.length === 0) {
              resolve();
            } else {
              setTimeout(checkComplete, 100);
            }
          };
          checkComplete();
        });
      },

      // 修改：处理中断时停止打字机
      abortResponse() {
        if (this.abortController) {
          this.abortController.abort();
          this.abortController = null;
          this.isAIResponding = false;
          this.isAbortable = false;

          // 停止打字机效果
          this.typewriterQueue = [];
          this.isTyping = false;

          // 找到最后一个AI消息并停止其打字状态
          const lastAiMessage = [...this.messages]
            .reverse()
            .find((m) => m.role === "ai");
          if (lastAiMessage) {
            this.$set(lastAiMessage, "isTyping", false);
            this.$set(lastAiMessage, "isStreaming", false);

            // 添加停止标记并重新渲染
            const stoppedContent = lastAiMessage.content + "\n\n*[回答已停止]*";
            this.$set(lastAiMessage, "content", stoppedContent);
            this.$set(
              lastAiMessage,
              "renderedContent",
              this.renderMarkdown(stoppedContent)
            );
          }

          this.$message.info("已停止生成回答");
        }
      },

      // 修改：处理API错误时停止打字机
      handleAPIError(error, aiMessage) {
        // 停止打字机效果
        this.typewriterQueue = [];
        this.isTyping = false;

        if (error.name === "AbortError") {
          console.log("请求已被取消");
          const currentContent = aiMessage.content || "";
          const stoppedContent = currentContent + "\n\n*[回答已停止]*";
          this.$set(aiMessage, "content", stoppedContent);
          this.$set(
            aiMessage,
            "renderedContent",
            this.renderMarkdown(stoppedContent)
          );
        } else {
          console.error("API请求错误:", error);
          const currentContent = aiMessage.content || "";
          const errorContent =
            currentContent + `\n\n**[请求出错: ${error.message}]**`;
          this.$set(aiMessage, "content", errorContent);
          this.$set(
            aiMessage,
            "renderedContent",
            this.renderMarkdown(errorContent)
          );
        }
        this.$set(aiMessage, "isTyping", false);
        this.$set(aiMessage, "isStreaming", false);
        this.isAIResponding = false;
        this.isAbortable = false;
      },

      scrollToBottom() {
        this.$nextTick(() => {
          const container = this.$refs.chatContainer;
          if (container) {
            container.scrollTop = container.scrollHeight;
            container.scrollTo({
              top: container.scrollHeight,
              behavior: "smooth",
            });
          }
        });
      },

      closeDia() {
        this.$emit("close");
      },
    },

    beforeDestroy() {
      if (this.abortController) {
        this.abortController.abort();
      }
      // 清理打字机状态
      this.typewriterQueue = [];
      this.isTyping = false;
    },
  };
</script>

<style lang="scss" scoped>
  $primary-color: #0356bd;
  $secondary-color: #0c1b37;
  $border-color: #31abfc;
  $shadow-color: #1855a2;
  $user-bubble: rgba(54, 96, 173, 1);
  $ai-bubble: rgba(28, 55, 105, 1);
  $text-color: #e6f7ff;

  .dialog_box {
    position: fixed;
    bottom: 24px;
    left: 0;
    width: 1920px;
    height: 1080px;
    z-index: 20;
    display: flex;
    align-items: flex-end;
    justify-content: center;

    .right {
      width: 879px;
      height: 959px;
      display: flex;
      flex-direction: column;
      position: relative;

      .close-btn {
        position: absolute;
        right: -18px;
        top: -18px;
        width: 36px;
        height: 36px;
        background: linear-gradient(45deg, #ff4757, #ff3742);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(255, 71, 87, 0.3);
        z-index: 100;

        &:hover {
          transform: scale(1.1);
          box-shadow: 0 6px 16px rgba(255, 71, 87, 0.4);
        }
      }

      // 新增：对话标题栏样式
      .dialog-header {
        height: 80px;
        background: linear-gradient(
          135deg,
          rgba(3, 86, 189, 0.95) 0%,
          rgba(12, 27, 55, 0.95) 100%
        );
        border: 1px solid #31abfc;
        border-radius: 16px 16px 0 0;
        padding: 16px 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: 0 2px 8px rgba(24, 85, 162, 0.3);
        backdrop-filter: blur(10px);

        .agent-info {
          display: flex;
          align-items: center;
          gap: 16px;

          .agent-avatar {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background: linear-gradient(45deg, #00fdfa, #0099cc);
            border: 2px solid #00fdfa;
            padding: 2px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 16px rgba(0, 253, 250, 0.4);

            .agent-avatar-image {
              width: 100%;
              height: 100%;
              border-radius: 50%;
              object-fit: cover;
            }
          }

          .agent-details {
            .agent-name {
              color: #00fdfa;
              font-size: 20px;
              font-weight: 700;
              margin: 0 0 4px 0;
              text-shadow: 0 2px 8px rgba(0, 253, 250, 0.5);
              letter-spacing: 1px;
            }

            .agent-description {
              color: rgba(255, 255, 255, 0.8);
              font-size: 14px;
              margin: 0;
              opacity: 0.95;
              font-weight: 400;
            }
          }
        }

        .connection-status {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 16px;
          background: rgba(0, 255, 136, 0.1);
          border: 1px solid rgba(0, 255, 136, 0.3);
          border-radius: 20px;
          backdrop-filter: blur(8px);

          .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;

            &.online {
              background: #00ff88;
              box-shadow: 0 0 12px #00ff88;
              animation: statusPulse 2s ease-in-out infinite;
            }
          }

          .status-text {
            color: #00ff88;
            font-size: 12px;
            font-weight: 600;
            text-shadow: 0 1px 4px rgba(0, 255, 136, 0.3);
          }
        }
      }

      .talk_1 {
        height: 691px; // 减去header高度后的剩余高度
        background: linear-gradient(
            180deg,
            #0356bd 0%,
            rgba(3, 86, 189, 0) 34%,
            rgba(3, 86, 189, 0) 51%,
            #0356bd 100%
          ),
          #0c1b37;
        box-shadow: 0px 4px 13px 4px #1855a2;
        border-left: 1px solid #31abfc;
        border-right: 1px solid #31abfc;
        opacity: 0.95;
        padding: 20px;
        overflow-y: auto;

        &::-webkit-scrollbar {
          width: 6px;
        }

        &::-webkit-scrollbar-track {
          background: rgba(255, 255, 255, 0.1);
          border-radius: 3px;
        }

        &::-webkit-scrollbar-thumb {
          background: rgba(49, 171, 252, 0.6);
          border-radius: 3px;

          &:hover {
            background: rgba(49, 171, 252, 0.8);
          }
        }

        .message_item {
          margin-bottom: 15px;
          padding: 10px 15px;
          border-radius: 8px;
          max-width: 80%;

          .message_item_center {
            width: 100%;
            word-wrap: break-word;
            display: flex;
            gap: 10px;
            align-items: flex-start;
          }

          .img_avatar {
            width: 56px;
            height: 56px;
            flex-shrink: 0;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(45deg, #0356bd, #31abfc);
            border: 2px solid #31abfc;
            margin-top: 8px;
            overflow: hidden;

            &.img_avatar_ai {
              background: linear-gradient(45deg, #00fdfa, #0099cc);
              border-color: #00fdfa;
            }

            &.img_avatar_user {
              width: 40px;
              height: 40px;
              background: linear-gradient(45deg, #31abfc, #0356bd);
              border-color: #31abfc;
              margin-top: 8px;
            }

            .avatar-image {
              width: 100%;
              height: 100%;
              object-fit: cover;
              border-radius: 50%;
              transition: all 0.3s ease;

              &.ai-thinking {
                animation: aiThinking 2s ease-in-out infinite;
                filter: drop-shadow(0 0 10px rgba(0, 253, 250, 0.6));
              }

              &.ai-speaking {
                animation: aiSpeaking 1.5s ease-in-out infinite;
                filter: drop-shadow(0 0 8px rgba(0, 253, 250, 0.4));
              }
            }

            // AI状态指示器
            .ai-status-indicator {
              position: absolute;
              bottom: -8px;
              right: -8px;
              background: rgba(0, 253, 250, 0.9);
              border-radius: 50%;
              padding: 4px;
              box-shadow: 0 2px 8px rgba(0, 253, 250, 0.4);

              .thinking-dots {
                display: flex;
                gap: 2px;

                span {
                  width: 3px;
                  height: 3px;
                  background: white;
                  border-radius: 50%;
                  animation: thinkingDots 1.5s ease-in-out infinite;

                  &:nth-child(2) {
                    animation-delay: 0.3s;
                  }

                  &:nth-child(3) {
                    animation-delay: 0.6s;
                  }
                }
              }
            }
          }

          .message-content {
            flex: 1;
            white-space: pre-wrap;
            word-break: break-word;
            border-radius: 16px;
            padding: 12px 16px;

            .msg_hd {
              margin-bottom: 12px;
              color: #00fdfa;
            }

            .msg_main {
              .msg_main_item {
                margin-bottom: 8px;

                &:hover span:last-child {
                  color: #31abfc;
                }
              }
            }

            // AI思考中文本样式
            .ai-thinking-text {
              color: rgba(255, 255, 255, 0.8);
              font-style: italic;
              display: flex;
              align-items: center;
              font-size: 16px;

              .thinking-dots-text {
                margin-left: 2px;
                display: inline-flex;

                .dot {
                  color: #00fdfa;
                  font-weight: bold;
                  font-size: 20px;
                  animation: thinkingTextDots 1.5s ease-in-out infinite;

                  &:nth-child(1) {
                    animation-delay: 0s;
                  }

                  &:nth-child(2) {
                    animation-delay: 0.3s;
                  }

                  &:nth-child(3) {
                    animation-delay: 0.6s;
                  }
                }
              }
            }

            // Markdown 内容样式
            .markdown-content {
              position: relative;
              color: white;

              // 添加流式输出的渐入效果
              animation: streamIn 0.3s ease-out;

              // 标题样式
              ::v-deep h1,
              ::v-deep h2,
              ::v-deep h3,
              ::v-deep h4,
              ::v-deep h5,
              ::v-deep h6 {
                color: #00fdfa;
                margin: 16px 0 8px 0;
                font-weight: bold;
              }

              ::v-deep h1 {
                font-size: 24px;
              }
              ::v-deep h2 {
                font-size: 22px;
              }
              ::v-deep h3 {
                font-size: 20px;
              }
              ::v-deep h4 {
                font-size: 18px;
              }
              ::v-deep h5 {
                font-size: 16px;
              }
              ::v-deep h6 {
                font-size: 14px;
              }

              // 段落样式
              ::v-deep p {
                // margin: 8px 0;
                line-height: 1.2;
              }

              // 列表样式
              ::v-deep ul,
              ::v-deep ol {
                padding-left: 24px;
              }
              ::v-deep ol li {
                list-style: decimal;
              }

              ::v-deep li {
                line-height: 1.2;
              }

              // 粗体和斜体
              ::v-deep strong {
                color: #31abfc;
                font-weight: bold;
              }

              ::v-deep em {
                color: #00ff88;
                font-style: italic;
              }

              // 行内代码样式
              ::v-deep .hljs-inline-code {
                background: rgba(255, 255, 255, 0.1);
                color: #ff6b6b;
                padding: 2px 6px;
                border-radius: 4px;
                font-family: "Consolas", "Monaco", "Courier New", monospace;
                font-size: 14px;
                border: 1px solid rgba(255, 255, 255, 0.2);
              }

              // 代码块样式
              ::v-deep .hljs-code-block {
                background: rgba(0, 0, 0, 0.6);
                border: 1px solid rgba(49, 171, 252, 0.3);
                border-radius: 8px;
                margin: 12px 0;
                overflow: hidden;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);

                code {
                  display: block;
                  padding: 16px;
                  overflow-x: auto;
                  font-family: "Consolas", "Monaco", "Courier New", monospace;
                  font-size: 14px;
                  line-height: 1.5;

                  &::-webkit-scrollbar {
                    height: 6px;
                  }

                  &::-webkit-scrollbar-track {
                    background: rgba(255, 255, 255, 0.1);
                    border-radius: 3px;
                  }

                  &::-webkit-scrollbar-thumb {
                    background: rgba(49, 171, 252, 0.6);
                    border-radius: 3px;

                    &:hover {
                      background: rgba(49, 171, 252, 0.8);
                    }
                  }
                }
              }

              // 引用样式
              ::v-deep blockquote {
                border-left: 4px solid #31abfc;
                margin: 12px 0;
                padding: 8px 16px;
                background: rgba(49, 171, 252, 0.1);
                font-style: italic;
                color: rgba(255, 255, 255, 0.9);
              }

              // 表格样式
              ::v-deep table {
                border-collapse: collapse;
                width: 100%;
                margin: 12px 0;
                background: rgba(255, 255, 255, 0.05);
                border-radius: 6px;
                overflow: hidden;
              }

              ::v-deep th,
              ::v-deep td {
                border: 1px solid rgba(49, 171, 252, 0.3);
                padding: 8px 12px;
                text-align: left;
              }

              ::v-deep th {
                background: rgba(49, 171, 252, 0.2);
                color: #00fdfa;
                font-weight: bold;
              }

              // 链接样式
              ::v-deep a {
                color: #31abfc;
                text-decoration: underline;
                transition: color 0.3s ease;

                &:hover {
                  color: #00fdfa;
                }
              }

              // 分割线样式
              ::v-deep hr {
                border: none;
                height: 2px;
                background: linear-gradient(
                  to right,
                  transparent,
                  #31abfc,
                  transparent
                );
                margin: 16px 0;
              }
            }

            // 流式输出状态样式
            &.streaming {
              position: relative;

              // 打字光标效果
              &::after {
                content: "";
                position: absolute;
                right: 8px;
                bottom: 8px;
                width: 2px;
                height: 16px;
                background: #00fdfa;
                animation: typingCursor 1s ease-in-out infinite;
              }
            }

            &.typing-animation {
              position: relative;

              &::after {
                content: "";
                position: absolute;
                right: 8px;
                bottom: 8px;
                width: 8px;
                height: 8px;
                background: #00fdfa;
                border-radius: 50%;
                animation: typingPulse 1s ease-in-out infinite;
              }
            }
          }

          // 流式输出光标（在打字时显示）
          .streaming-cursor {
            color: #00fdfa;
            font-size: 16px;
            font-weight: bold;
            animation: streamingCursorBlink 1s ease-in-out infinite;
            margin-left: 2px;
          }

          &.user {
            margin-left: auto;

            .message-content {
              background: rgba(49, 171, 252, 0.2);
              border: 1px solid #31abfc;
              color: white;
            }
          }

          &.ai {
            margin-right: auto;

            .message-content {
              background: rgba(12, 27, 55, 0.7);
              border: 1px solid #0356bd;
              color: white;

              // 消息完成时的动画
              &.message-complete {
                animation: messageComplete 0.5s ease-out;
              }
            }
          }
        }
      }

      .talk_2 {
        margin-top: 0; // 移除顶部间距，因为现在有header
        flex: 1;
        width: 100%;
        background: #0356bd;
        box-shadow: 0px 4px 13px 4px #1855a2;
        border-radius: 0 0 16px 16px;
        border: 1px solid #31abfc;
        opacity: 0.95;
        display: flex;
        flex-direction: column;
        align-items: center;

        .message-input {
          flex-grow: 1;
          border-radius: 8px;
          color: white;
          padding: 0 15px;
          font-size: 20px;

          &::placeholder {
            color: rgba(255, 255, 255, 0.5);
          }

          &:disabled {
            opacity: 0.7;
            cursor: not-allowed;
          }
        }

        .detail {
          flex: 1;
          width: 100%;
          display: flex;
          color: white;
          justify-content: flex-end;
          align-items: center;
          padding: 2px 0;

          .num {
            font-size: 14px;
            opacity: 0.8;
          }
        }

        .send-button {
          margin-right: 16px;
          height: 28px;
          width: 100px;
          background: #31abfc;
          border: none;
          border-radius: 8px;
          color: white;
          font-weight: bold;
          cursor: pointer;
          transition: background 0.3s;
          margin-left: 24px;

          &:hover:not(:disabled) {
            background: #1e90ff;
          }

          &:disabled {
            background: #7a7a7a;
            cursor: not-allowed;
          }

          &.abort-button {
            background: #ff4757;

            &:hover {
              background: #ff3742;
            }
          }
        }
      }
    }

    // 状态指示器动画
    @keyframes statusPulse {
      0%,
      100% {
        opacity: 1;
        transform: scale(1);
      }
      50% {
        opacity: 0.6;
        transform: scale(1.3);
      }
    }

    // 新增动画定义
    @keyframes aiThinking {
      0%,
      100% {
        transform: scale(1) rotate(0deg);
        filter: drop-shadow(0 0 10px rgba(0, 253, 250, 0.6));
      }
      25% {
        transform: scale(1.05) rotate(2deg);
        filter: drop-shadow(0 0 15px rgba(0, 253, 250, 0.8));
      }
      50% {
        transform: scale(1.1) rotate(0deg);
        filter: drop-shadow(0 0 20px rgba(0, 253, 250, 1));
      }
      75% {
        transform: scale(1.05) rotate(-2deg);
        filter: drop-shadow(0 0 15px rgba(0, 253, 250, 0.8));
      }
    }

    @keyframes aiSpeaking {
      0%,
      100% {
        transform: scale(1);
        filter: drop-shadow(0 0 8px rgba(0, 253, 250, 0.4));
      }
      50% {
        transform: scale(1.02);
        filter: drop-shadow(0 0 12px rgba(0, 253, 250, 0.6));
      }
    }

    @keyframes thinkingDots {
      0%,
      20%,
      80%,
      100% {
        opacity: 0.3;
        transform: scale(1);
      }
      50% {
        opacity: 1;
        transform: scale(1.2);
      }
    }

    @keyframes thinkingTextDots {
      0%,
      20%,
      80%,
      100% {
        opacity: 0.3;
        transform: scale(1);
      }
      50% {
        opacity: 1;
        transform: scale(1.2);
      }
    }

    @keyframes typingPulse {
      0%,
      100% {
        opacity: 0.3;
        transform: scale(1);
      }
      50% {
        opacity: 1;
        transform: scale(1.3);
      }
    }

    @keyframes messageComplete {
      0% {
        transform: scale(1);
        box-shadow: 0 0 0 rgba(0, 253, 250, 0.4);
      }
      50% {
        transform: scale(1.02);
        box-shadow: 0 0 20px rgba(0, 253, 250, 0.6);
      }
      100% {
        transform: scale(1);
        box-shadow: 0 0 0 rgba(0, 253, 250, 0.4);
      }
    }

    @keyframes slideInFromLeft {
      0% {
        transform: translateX(-20px);
        opacity: 0;
      }
      100% {
        transform: translateX(0);
        opacity: 1;
      }
    }

    @keyframes streamIn {
      0% {
        opacity: 0;
        transform: translateY(10px);
      }
      100% {
        opacity: 1;
        transform: translateY(0);
      }
    }

    @keyframes blink {
      0%,
      100% {
        opacity: 1;
      }
      50% {
        opacity: 0;
      }
    }

    ::v-deep {
      .el-textarea {
        height: 100%;
        width: 100%;

        &__inner {
          width: 100%;
          height: 100%;
          background: transparent;
          border: none;
          font-size: 20px;
          color: $text-color;
          resize: none;

          &.is-focus {
            outline: none;
          }

          &::placeholder {
            color: $text-color;
            opacity: 0.7;
          }
        }
      }
    }
  }

  // 为正在打字的消息添加特殊样式
  .message_item.ai .message-content.streaming {
    &::before {
      content: "";
      position: absolute;
      left: -3px;
      top: 0;
      width: 3px;
      height: 100%;
      background: linear-gradient(
        to bottom,
        transparent 0%,
        #00fdfa 20%,
        #00fdfa 80%,
        transparent 100%
      );
      animation: streamingProgress 2s ease-in-out infinite;
    }
  }

  @keyframes streamingProgress {
    0% {
      opacity: 0.3;
      transform: scaleY(0.5);
    }
    50% {
      opacity: 0.8;
      transform: scaleY(1);
    }
    100% {
      opacity: 0.3;
      transform: scaleY(0.5);
    }
  }

  // 新增：打字光标动画
  @keyframes typingCursor {
    0%,
    50% {
      opacity: 1;
      transform: scaleY(1);
    }
    51%,
    100% {
      opacity: 0.3;
      transform: scaleY(0.8);
    }
  }

  // 改进现有的动画，使其更平滑
  @keyframes streamingCursorBlink {
    0%,
    50% {
      opacity: 1;
      transform: scaleX(1);
    }
    51%,
    100% {
      opacity: 0.3;
      transform: scaleX(0.6);
    }
  }
</style>
